package com.yunshan.order.service.impl;

import com.yunshan.common.annotation.DataScope;
import com.yunshan.common.utils.*;
import com.yunshan.common.utils.uuid.UUID;
import com.yunshan.member.domain.MemberSubCardInfo;
import com.yunshan.member.domain.MemberUserInfo;
import com.yunshan.member.domain.ResultMember;
import com.yunshan.member.service.IMemberSubCardInfoService;
import com.yunshan.member.service.IMemberUserInfoService;
import com.yunshan.mp.domain.MpIndexActivityNotice;
import com.yunshan.mp.domain.MpServeInfo;
import com.yunshan.mp.service.IMpIndexActivityNoticeService;
import com.yunshan.mp.service.IMpServeInfoService;
import com.yunshan.order.domain.OrderConsumeRecord;
import com.yunshan.order.domain.OrderReserveNotice;
import com.yunshan.order.domain.ReserveVo;
import com.yunshan.order.mapper.OrderReserveNoticeMapper;
import com.yunshan.order.service.IOrderConsumeRecordService;
import com.yunshan.order.service.IOrderReserveNoticeService;
import com.yunshan.wechat.domain.UserInfoVo;
import com.yunshan.wechat.domain.WechatUserInfo;
import com.yunshan.wechat.service.IWechatUserInfoService;
import com.yunshan.welfare.domain.*;
import com.yunshan.welfare.service.IWelfareCouponRecordService;
import com.yunshan.welfare.service.IWelfareCouponService;
import com.yunshan.welfare.service.IWelfareGiftContentService;
import com.yunshan.welfare.service.IWelfareGiftRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 预约通知Service业务层处理
 *
 * @author yunshan
 * @date 2025-01-17
 */
@Service
public class OrderReserveNoticeServiceImpl implements IOrderReserveNoticeService
{
    @Autowired
    private OrderReserveNoticeMapper orderReserveNoticeMapper;
    @Autowired
    private IMemberUserInfoService memberUserInfoService;
    @Autowired
    private IMemberSubCardInfoService memberSubCardInfoService;
    @Autowired
    private IOrderConsumeRecordService orderConsumeRecordService;
    @Autowired
    private IMpIndexActivityNoticeService mpIndexActivityNoticeService;
    @Autowired
    private IWechatUserInfoService wechatUserInfoService;
    @Autowired
    private IMpServeInfoService mpServeInfoService;
    @Autowired
    private IWelfareCouponRecordService welfareCouponRecordService;
    @Autowired
    private IWelfareCouponService welfareCouponService;
    @Autowired
    private IWelfareGiftRecordService welfareGiftRecordService;
    @Autowired
    private IWelfareGiftContentService welfareGiftContentService;

    /**
     * 查询预约通知
     *
     * @param id 预约通知主键
     * @return 预约通知
     */
    @Override
    public OrderReserveNotice selectOrderReserveNoticeById(Long id)
    {
        OrderReserveNotice orderReserveNotice = orderReserveNoticeMapper.selectOrderReserveNoticeById(id);

        if (orderReserveNotice.getCardType() == 1){
            ResultMember memberUserInfo = memberUserInfoService.selectResultMember(orderReserveNotice.getMemberId());
            if (memberUserInfo != null){
                orderReserveNotice.setResultNotice(memberUserInfo);
            }
        }else {
            ResultMember memberSubCardInfo = memberSubCardInfoService.selectResultMember(orderReserveNotice.getMemberId());
            if (memberSubCardInfo != null){
                orderReserveNotice.setResultNotice(memberSubCardInfo);
            }
        }

        return orderReserveNotice;
    }

    /**
     * 查询预约通知列表
     *
     * @param orderReserveNotice 预约通知
     * @return 预约通知
     */
    @Override
    @DataScope(deptAlias = "order_reserve_notice")
    public List<OrderReserveNotice> selectOrderReserveNoticeList(OrderReserveNotice orderReserveNotice)
    {
        return orderReserveNoticeMapper.selectOrderReserveNoticeList(orderReserveNotice);
    }

    /**
     * 新增预约通知
     *
     * @param orderReserveNotice 预约通知
     * @return 结果
     */
    @Override
    public int insertOrderReserveNotice(OrderReserveNotice orderReserveNotice)
    {
        orderReserveNotice.setCreateTime(DateUtils.getNowDate());
        return orderReserveNoticeMapper.insertOrderReserveNotice(orderReserveNotice);
    }

    /**
     * 修改预约通知
     *
     * @param orderReserveNotice 预约通知
     * @return 结果
     */
    @Override
    public int updateOrderReserveNotice(OrderReserveNotice orderReserveNotice)
    {
        OrderReserveNotice reserveNotice = orderReserveNoticeMapper.selectOrderReserveNoticeById(orderReserveNotice.getId());
        if (reserveNotice == null){
            throw new RuntimeException("取消预约异常");
        }

        //更新礼包的优惠券状态
        if (reserveNotice.getPayType() == 2){
            //判断礼包是否过期
            WelfareGiftRecord welfareGiftRecord = new WelfareGiftRecord();
            welfareGiftRecord.setId(reserveNotice.getServeId());
            WelfareGiftRecord giftRecord = welfareGiftRecordService.selectWelfareGiftRecordById(reserveNotice.getServeId());
            if (giftRecord.getEndTime().before(new Date())){
                welfareGiftRecord.setStatus(2);
            }else {
                welfareGiftRecord.setStatus(0);
            }

            int i = welfareGiftRecordService.updateWelfareGiftRecord(welfareGiftRecord);
            if (i < 1){
                throw new RuntimeException("取消失败，请重试");
            }

        //更新优惠券状态
        }else if (reserveNotice.getPayType() == 3){
            WelfareCouponRecord welfareCouponRecord = new WelfareCouponRecord();
            welfareCouponRecord.setId(reserveNotice.getServeId());

            //判断优惠券是否过期
            WelfareCouponRecord couponRecord = welfareCouponRecordService.selectWelfareCouponRecordById(reserveNotice.getServeId());
            if (couponRecord.getEndTime().before(new Date())){
                welfareCouponRecord.setStatus(2);
            }else {
                welfareCouponRecord.setStatus(0);
                int i = welfareCouponRecordService.updateWelfareCouponRecord(couponRecord);
                if (i < 1){
                    throw new RuntimeException("取消失败，请重试");
                }
            }

        }


        return orderReserveNoticeMapper.updateOrderReserveNotice(orderReserveNotice);
    }

    /**
     * 批量删除预约通知
     *
     * @param ids 需要删除的预约通知主键
     * @return 结果
     */
    @Override
    public int deleteOrderReserveNoticeByIds(Long[] ids)
    {
        return orderReserveNoticeMapper.deleteOrderReserveNoticeByIds(ids);
    }

    /**
     * 删除预约通知信息
     *
     * @param id 预约通知主键
     * @return 结果
     */
    @Override
    public int deleteOrderReserveNoticeById(Long id)
    {
        return orderReserveNoticeMapper.deleteOrderReserveNoticeById(id);
    }

    @Override
    public int verifyOrderReserveNotice(OrderReserveNotice orderReserveNotice) {
        //核销券码
        OrderReserveNotice order = orderReserveNoticeMapper.selectOrderReserveNoticeById(orderReserveNotice.getId());
        if (!order.getCode().equals(orderReserveNotice.getCode())){
            throw new RuntimeException("券码不正确，请重新核销");
        }

        //生成订单号
        String orderNumber = UUID.generateOrderNumber();

        //生成消费订单
        OrderConsumeRecord orderConsumeRecord = new OrderConsumeRecord();
        orderConsumeRecord.setMemberId(orderReserveNotice.getMemberId());
        orderConsumeRecord.setOrderNum(orderNumber);
        orderConsumeRecord.setName(orderReserveNotice.getName());
        orderConsumeRecord.setPhone(orderReserveNotice.getPhone());
        orderConsumeRecord.setPayType(orderReserveNotice.getPayType());
        orderConsumeRecord.setServeId(orderReserveNotice.getServeId());
        orderConsumeRecord.setServeName(orderReserveNotice.getServeName());
        orderConsumeRecord.setServeType(orderReserveNotice.getServeType());
        if("1".equals(orderReserveNotice.getServeType())){
            orderConsumeRecord.setNum(orderReserveNotice.getNum());
        }
        if (orderReserveNotice.getPayType() == 2){
            orderConsumeRecord.setGiftRecordId(orderReserveNotice.getGiftId());
        }else if (orderReserveNotice.getPayType() == 3){
            orderConsumeRecord.setCouponRecordId(orderReserveNotice.getCouponId());
        }
        orderConsumeRecord.setVerifyType(1);
        orderConsumeRecord.setCouponCode(order.getCouponCode());
        orderConsumeRecord.setCardType(order.getCardType());

        //新增消费订单
        orderConsumeRecordService.insertOrderConsumeRecord(orderConsumeRecord);

        //更新预约通知
        orderReserveNotice.setOrderNum(orderNumber);
        orderReserveNotice.setUseTime(DateUtils.getNowDate());
        orderReserveNotice.setUpdateTime(DateUtils.getNowDate());
        orderReserveNotice.setStatus(1);
        return orderReserveNoticeMapper.updateOrderReserveNotice(orderReserveNotice);
    }

    @Override
    public ReserveVo insertActivityReserve(ReserveVo reserveVo) {
        //活动预约
        OrderReserveNotice orderReserveNotice = new OrderReserveNotice();
        orderReserveNotice.setName(reserveVo.getName());
        orderReserveNotice.setPhone(reserveVo.getPhone());
        orderReserveNotice.setReserveType(2);
        if (StringUtils.isNotEmpty(reserveVo.getRoomNumber())) {
            orderReserveNotice.setRoomNumber(reserveVo.getRoomNumber());
        }
        orderReserveNotice.setRemark(reserveVo.getRemark());
        orderReserveNotice.setServeId(reserveVo.getServeId());

        //查询活动公告
        MpIndexActivityNotice mpIndexActivityNotice = mpIndexActivityNoticeService.selectMpIndexActivityNoticeById(reserveVo.getServeId());
        orderReserveNotice.setServeName(mpIndexActivityNotice.getTitle());
        reserveVo.setServeName(mpIndexActivityNotice.getTitle());

        //获取会员id
        WechatUserInfo wechatUserInfo = wechatUserInfoService.selectWechatUserInfoById(UserUtils.getUserId());
        if (wechatUserInfo == null){
            throw new RuntimeException("获取用户信息异常");
        }

        //判断是主卡or副卡，存储会员id
        if (wechatUserInfo.getType() == 1){
            MemberUserInfo memberUserInfo = memberUserInfoService.selectUserInfoByUserId(wechatUserInfo.getId());
            if (memberUserInfo != null){
                orderReserveNotice.setMemberId(memberUserInfo.getId());
            }

        }else {
            MemberSubCardInfo memberSubCardInfo = memberSubCardInfoService.selectUserInfoByUserId(wechatUserInfo.getId());
            if (memberSubCardInfo != null){
                orderReserveNotice.setMemberId(memberSubCardInfo.getId());
            }
        }

        orderReserveNotice.setCardType(wechatUserInfo.getType());

        //预约时间
        orderReserveNotice.setReserveTime(DateUtils.getNowDate());
        orderReserveNotice.setCreateTime(DateUtils.getNowDate());

        orderReserveNoticeMapper.insertOrderReserveNotice(orderReserveNotice);
        return reserveVo;
    }

    @Override
    public Integer selectReserveCount(Long id) {
        return orderReserveNoticeMapper.selectReserveCount(id);
    }

    @Override
    public ReserveVo insertServeReserve(ReserveVo reserveVo) {
        try {
            //服务
            OrderReserveNotice orderReserveNotice = new OrderReserveNotice();
            orderReserveNotice.setName(reserveVo.getName());
            orderReserveNotice.setPhone(reserveVo.getPhone());
            orderReserveNotice.setReserveType(1);
            if (StringUtils.isNotEmpty(reserveVo.getRoomNumber())) {
                orderReserveNotice.setRoomNumber(reserveVo.getRoomNumber());
            }
            orderReserveNotice.setServeId(reserveVo.getServeId());
            if (StringUtils.isNotEmpty(reserveVo.getRemark())) {
                orderReserveNotice.setRemark(reserveVo.getRemark());
            }

            //消费方式
            if (reserveVo.getPayType() == null){
                orderReserveNotice.setPayType(1);
            }else {
                orderReserveNotice.setPayType(reserveVo.getPayType());
            }

            //获取会员id
            WechatUserInfo wechatUserInfo = wechatUserInfoService.selectWechatUserInfoById(UserUtils.getUserId());
            if (wechatUserInfo == null) {
                throw new RuntimeException("获取用户信息异常");
            }

            //判断是主卡or副卡，存储会员id
            if (wechatUserInfo.getType() == 1) {
                MemberUserInfo memberUserInfo = memberUserInfoService.selectUserInfoByUserId(wechatUserInfo.getId());
                if (memberUserInfo != null) {
                    orderReserveNotice.setMemberId(memberUserInfo.getId());
                }

            } else {
                MemberSubCardInfo memberSubCardInfo = memberSubCardInfoService.selectUserInfoByUserId(wechatUserInfo.getId());
                if (memberSubCardInfo != null) {
                    orderReserveNotice.setMemberId(memberSubCardInfo.getId());
                }
            }

            orderReserveNotice.setCardType(wechatUserInfo.getType());

            //查询服务，服务预约
            if (orderReserveNotice.getPayType() == 1) {
                MpServeInfo mpServeInfo = mpServeInfoService.selectMpServeInfoById(reserveVo.getServeId());
                orderReserveNotice.setServeName(mpServeInfo.getName());
                orderReserveNotice.setServeType(mpServeInfo.getServeType());
                reserveVo.setServeName(mpServeInfo.getName());

            //优惠券预约
            }else if (orderReserveNotice.getPayType() == 3) {
                orderReserveNotice.setCouponId(reserveVo.getServeId());
                WelfareCouponRecord welfareCouponRecord = welfareCouponRecordService.selectWelfareCouponRecordById(reserveVo.getServeId());
                WelfareCoupon welfareCoupon = welfareCouponService.selectWelfareCouponById(welfareCouponRecord.getCouponId());

                if (welfareCoupon == null || welfareCoupon.getStatus() != 0){
                    throw new RuntimeException("优惠券已使用或已过期");
                }

                orderReserveNotice.setServeName(welfareCoupon.getName());
                orderReserveNotice.setServeType(welfareCoupon.getServeType());
                reserveVo.setServeName(welfareCoupon.getName());
                welfareCouponRecord.setStatus(3);
                welfareCouponRecord.setUseTime(new Date());
                welfareCouponRecordService.updateWelfareCouponRecord(welfareCouponRecord);

            //礼包预约
            }else if (orderReserveNotice.getPayType() == 2){
                WelfareGiftRecord welfareGiftRecord = welfareGiftRecordService.selectWelfareGiftRecordById(reserveVo.getServeId());

                if (welfareGiftRecord == null || welfareGiftRecord.getStatus() != 0){
                    throw new RuntimeException("礼包优惠券已使用或已过期");
                }

                orderReserveNotice.setGiftId(welfareGiftRecord.getGiftContentId());
                WelfareGiftRecord giftRecord = new WelfareGiftRecord();
                giftRecord.setGiftContentId(welfareGiftRecord.getGiftContentId());
                giftRecord.setMemberId(welfareGiftRecord.getMemberId());
                giftRecord.setStatus(0);

                List<WelfareGiftRecord> welfareGiftRecords = welfareGiftRecordService.selectWelfareGiftRecordList(giftRecord);
                if (welfareGiftRecords.size() < 1){
                    throw new RuntimeException("礼包优惠券已使用或已过期");
                }
                WelfareGiftContent welfareGiftContent = welfareGiftContentService.selectWelfareGiftContentById(welfareGiftRecord.getGiftContentId());


                orderReserveNotice.setServeName(welfareGiftContent.getContentName());
                orderReserveNotice.setServeType(welfareGiftContent.getServeType());
                reserveVo.setServeName(welfareGiftContent.getContentName());
                giftRecord.setId(welfareGiftRecord.getId());
                giftRecord.setStatus(1);
                welfareGiftRecordService.updateWelfareGiftRecord(giftRecord);
            }

            //生成核销码
            // 生成一个6位的随机数并验证是否存在
            Random random = new Random();
            int randomNumber = 0;
            int i = 1;
            while (i > 0) {
                randomNumber = 100000 + random.nextInt(900000); // 生成6位随机数
                i = orderReserveNoticeMapper.verifyCode(randomNumber);
            }
            orderReserveNotice.setCode(String.valueOf(randomNumber));

            //生成券码
            orderReserveNotice.setCouponCode(UUID.generateCouponCode());

            //预约时间
            orderReserveNotice.setReserveTime(reserveVo.getReserveTime());
            orderReserveNotice.setCreateTime(DateUtils.getNowDate());
            orderReserveNoticeMapper.insertOrderReserveNotice(orderReserveNotice);
            return reserveVo;
        }catch (Exception e){
            throw new RuntimeException("预约失败");
        }
    }

    @Override
    public List<ReserveVo> selectUniReserveNotice(OrderReserveNotice orderReserveNotice) {
        try {

            Long userId = UserUtils.getUserId();
            //判断类型主卡or副卡
            WechatUserInfo wechatUserInfo = wechatUserInfoService.selectWechatUserInfoById(userId);
            if (wechatUserInfo.getType() == 1){
                orderReserveNotice.setMemberId(memberUserInfoService.selectUserInfoByUserId(userId).getId());
                orderReserveNotice.setCardType(1);
            }else {
                orderReserveNotice.setMemberId(memberSubCardInfoService.selectUserInfoByUserId(userId).getId());
                orderReserveNotice.setCardType(2);
            }
            List<ReserveVo> reserveVos = orderReserveNoticeMapper.selectUniReserveNotice(orderReserveNotice);
            //存入服务金额和图片
            for (ReserveVo reserveVo : reserveVos) {
                //余额消费
                if (reserveVo.getPayType() == 1) {
                    MpServeInfo mpServeInfo = mpServeInfoService.selectMpServeInfoById(reserveVo.getServeId());
                    reserveVo.setAmount(mpServeInfo.getPrice());
                    reserveVo.setImg(mpServeInfo.getProjectImg());

                //优惠券
                }else if (reserveVo.getPayType() == 3){
                    WelfareCouponRecord welfareCouponRecord = welfareCouponRecordService.selectWelfareCouponRecordById(reserveVo.getServeId());
                    WelfareCoupon welfareCoupon = welfareCouponService.selectWelfareCouponById(welfareCouponRecord.getCouponId());
                    reserveVo.setAmount(welfareCoupon.getPrice());
                    reserveVo.setImg(welfareCoupon.getCouponImg());
                //礼包
                }else{
                    Long contentId = welfareGiftContentService.selectWelfareGiftContentById(reserveVo.getGiftId()).getContentId();
                    WelfareCoupon welfareCoupon = welfareCouponService.selectWelfareCouponById(contentId);
                    reserveVo.setImg(welfareCoupon.getCouponImg());
                }

            }
            return reserveVos;
        }catch (Exception e){
            return null;
        }
    }

    @Override
    public ReserveVo selectUniReserveNoticeInfo(Long id) {
        ReserveVo reserveVo = orderReserveNoticeMapper.selectUniReserveNoticeInfo(id);

        Long userId = UserUtils.getUserId();
        //判断类型主卡or副卡
        WechatUserInfo wechatUserInfo = wechatUserInfoService.selectWechatUserInfoById(userId);
        UserInfoVo userInfoVo;
        if (wechatUserInfo.getType() == 1){
            userInfoVo = memberUserInfoService.selectUniUserInfo(userId);

        }else {
            userInfoVo = memberSubCardInfoService.selectUniUserInfo(userId);
        }

        //会员信息
        reserveVo.setMemberName(userInfoVo.getName());
        reserveVo.setMemberPhone(StringUtil.encryptPhoneNumber(userInfoVo.getPhone()));

        //存入服务金额和图片
        if (reserveVo.getPayType() == 1) {
            MpServeInfo mpServeInfo = mpServeInfoService.selectMpServeInfoById(reserveVo.getServeId());
            reserveVo.setAmount(mpServeInfo.getPrice());
            reserveVo.setImg(mpServeInfo.getProjectImg());

        //礼包预约
        }else if (reserveVo.getPayType() == 2){
            WelfareGiftRecord welfareGiftRecord = welfareGiftRecordService.selectWelfareGiftRecordById(reserveVo.getServeId());
            Long contentId = welfareGiftContentService.selectWelfareGiftContentById(welfareGiftRecord.getGiftContentId()).getContentId();
            WelfareCoupon welfareCoupon = welfareCouponService.selectWelfareCouponById(contentId);

            reserveVo.setAmount(welfareCoupon.getPrice());
            reserveVo.setImg(welfareCoupon.getCouponImg());

        //优惠券预约
        }else {
            WelfareCouponRecord welfareCouponRecord = welfareCouponRecordService.selectWelfareCouponRecordById(reserveVo.getServeId());
            if (welfareCouponRecord == null){
                return reserveVo;
            }
            WelfareCoupon welfareCoupon = welfareCouponService.selectWelfareCouponById(welfareCouponRecord.getCouponId());

            reserveVo.setAmount(welfareCoupon.getPrice());
            reserveVo.setImg(welfareCoupon.getCouponImg());
        }
        return reserveVo;
    }
}
